import { getText, getParsedText } from '../../store/txtstore.js'
import jsonToMap from '../../j2m.js'
import skilldata from '../../data/BattleSkillData.json'
import displaydata from '../../data/BattleSkillDisplayData.json'
import buffdata from '../../data/BattleBuffPerformData.json'
import hintdata from '../../data/HintData.json'

const skills = jsonToMap(skilldata.data)
const displays = jsonToMap(displaydata.data)
const buffs = jsonToMap(buffdata.data)
const hints = jsonToMap(hintdata.data)

function getSkill(sid) {
  const skill = skills.get(sid)
  const display = displays.get(sid)
  if (!display || !display[12]) {
    return
  }
  const name = getText(display[2][1])
  let defBreak = undefined
  if (skill[17]) {
    const segment = skill[17].match(/;2,\d+,\d+,\d+,/)
    if (segment) {
      defBreak = segment[0].split(',')[1]
    }
  }
  return {
    name: name,
    descLv: getParsedText(display[3][1]),
    desc: getParsedText(display[5][1]),
    intro: getParsedText(display[6][1]),
    lv: display[9],
    icon: display[10],
    tag: getText(display[22][1]),
    elem: skill[6],
    defBreak: defBreak,
    rangeType: skill[22],
    range: skill[23],
    areaType: skill[24],
    area: skill[25],
    cd: skill[31],
    mp: skill[34],
    buff: getBuff(display[4]),
    weaponElem: skill[45]
  }
}

function getBuff(str) {
  if (str === undefined) {
    return undefined
  }
  const pairs = str.split(';').map(pair => pair.split(':')).filter(p => p.length > 1)
  const lst = []
  for (const [k, v] of pairs) {
    if (+k) {
      lst.push(getParsedText(hints.get(+v)[2][1]))
    } else if (!v.includes(',')) {
      const buff = buffs.get(+v)
      if (!buff) {
        continue
      }
      const name = getText(buff[2][1])
      const descId = buff[3][1]
      lst.push(`<span style="color:#3487e0;">${name}</span>：${getParsedText(descId)}`)
    }
  }
  return lst
}

function groupSkills(sids) {
  const groups = new Map()
  const gis = new Set(sids.map(k => String(k).charAt(6)))
  for (const gi of gis) {
    groups.set(+gi, [])
  }
  for (const k of sids) {
    const gi = String(k).charAt(6)
    const skill = getSkill(k)
    if (skill) {
      groups.get(+gi).push(getSkill(k))
    }
  }
  return groups
}

function getSkills(uid) {
  const sids = []
  for (const k of skills.keys()) {
    if (Math.floor(k/10000) == uid) {
      sids.push(k)
    }
  }
  const ret = [['attack', getSkill(uid*10000+101)]]
  const map = [0, 5, 7, 4, 8]
  for (let i = 1; i < 5; i++) {
    ret.push([i, groupSkills(sids.filter(k => String(k).charAt(5) == map[i]))])
  }
  return new Map(ret)
}

function getLvUpDesc(sid) {
  return getParsedText(displays.get(+sid)[8][1])
}

export { getSkill, getSkills, getLvUpDesc }